use std::path::Path;
use sled::{Db, Tree};
use chrono::{DateTime, Utc};
use serde_json;
use tracing::{info, error, debug};

use crate::storage::{DataPoint, DeviceStatus};
use crate::error::{Result, ModbusCollectorError};

/// 持久化存储（基于Sled嵌入式数据库）
#[derive(Debug, Clone)]
pub struct PersistentStorage {
    db: Db,
    data_tree: Tree,
    device_tree: Tree,
    config_tree: Tree,
}

impl PersistentStorage {
    pub async fn new<P: AsRef<Path>>(db_path: P) -> Result<Self> {
        info!("Opening persistent storage at: {:?}", db_path.as_ref());
        
        let db = sled::open(db_path)
            .map_err(|e| ModbusCollectorError::Storage(format!("Failed to open database: {}", e)))?;
        
        let data_tree = db.open_tree("data")
            .map_err(|e| ModbusCollectorError::Storage(format!("Failed to open data tree: {}", e)))?;
        
        let device_tree = db.open_tree("devices")
            .map_err(|e| ModbusCollectorError::Storage(format!("Failed to open device tree: {}", e)))?;
        
        let config_tree = db.open_tree("config")
            .map_err(|e| ModbusCollectorError::Storage(format!("Failed to open config tree: {}", e)))?;
        
        info!("Persistent storage initialized successfully");
        
        Ok(Self {
            db,
            data_tree,
            device_tree,
            config_tree,
        })
    }
    
    /// 存储历史数据点
    pub async fn store_historical_data(&self, data_point: &DataPoint) -> Result<()> {
        let key = format!("{}:{}", data_point.point_id, data_point.timestamp.timestamp_millis());
        let value = serde_json::to_vec(data_point)?;
        
        self.data_tree.insert(key.as_bytes(), value)
            .map_err(|e| ModbusCollectorError::Storage(format!("Failed to store data point: {}", e)))?;
        
        debug!("Stored historical data point: {}", data_point.point_id);
        Ok(())
    }
    
    /// 获取历史数据
    pub async fn get_historical_data(
        &self,
        point_id: &str,
        start_time: Option<DateTime<Utc>>,
        end_time: Option<DateTime<Utc>>,
        limit: Option<usize>,
    ) -> Result<Vec<DataPoint>> {
        let start_key = match start_time {
            Some(time) => format!("{}:{}", point_id, time.timestamp_millis()),
            None => format!("{}:", point_id),
        };
        
        let end_key = match end_time {
            Some(time) => format!("{}:{}", point_id, time.timestamp_millis()),
            None => format!("{}:~", point_id),
        };
        
        let mut results = Vec::new();
        let iter = self.data_tree.range(start_key.as_bytes()..end_key.as_bytes());
        
        for item in iter {
            match item {
                Ok((_, value)) => {
                    match serde_json::from_slice::<DataPoint>(&value) {
                        Ok(data_point) => {
                            results.push(data_point);
                            if let Some(limit) = limit {
                                if results.len() >= limit {
                                    break;
                                }
                            }
                        },
                        Err(e) => {
                            error!("Failed to deserialize data point: {}", e);
                        }
                    }
                },
                Err(e) => {
                    error!("Database iteration error: {}", e);
                }
            }
        }
        
        // 按时间排序
        results.sort_by(|a, b| a.timestamp.cmp(&b.timestamp));
        
        debug!("Retrieved {} historical data points for {}", results.len(), point_id);
        Ok(results)
    }
    
    /// 存储设备状态
    pub async fn store_device_status(&self, status: &DeviceStatus) -> Result<()> {
        let key = status.device_id.as_bytes();
        let value = serde_json::to_vec(status)?;
        
        self.device_tree.insert(key, value)
            .map_err(|e| ModbusCollectorError::Storage(format!("Failed to store device status: {}", e)))?;
        
        debug!("Stored device status: {}", status.device_id);
        Ok(())
    }
    
    /// 获取设备状态
    pub async fn get_device_status(&self, device_id: &str) -> Result<Option<DeviceStatus>> {
        match self.device_tree.get(device_id.as_bytes()) {
            Ok(Some(value)) => {
                let status = serde_json::from_slice(&value)?;
                Ok(Some(status))
            },
            Ok(None) => Ok(None),
            Err(e) => Err(ModbusCollectorError::Storage(format!("Failed to get device status: {}", e))),
        }
    }
    
    /// 获取所有设备状态
    pub async fn get_all_device_status(&self) -> Result<Vec<DeviceStatus>> {
        let mut results = Vec::new();
        
        for item in self.device_tree.iter() {
            match item {
                Ok((_, value)) => {
                    match serde_json::from_slice::<DeviceStatus>(&value) {
                        Ok(status) => results.push(status),
                        Err(e) => error!("Failed to deserialize device status: {}", e),
                    }
                },
                Err(e) => error!("Device tree iteration error: {}", e),
            }
        }
        
        Ok(results)
    }
    
    /// 存储配置信息
    pub async fn store_config(&self, key: &str, value: &str) -> Result<()> {
        self.config_tree.insert(key.as_bytes(), value.as_bytes())
            .map_err(|e| ModbusCollectorError::Storage(format!("Failed to store config: {}", e)))?;
        
        debug!("Stored config: {}", key);
        Ok(())
    }
    
    /// 获取配置信息
    pub async fn get_config(&self, key: &str) -> Result<Option<String>> {
        match self.config_tree.get(key.as_bytes()) {
            Ok(Some(value)) => {
                let config = String::from_utf8(value.to_vec())
                    .map_err(|e| ModbusCollectorError::Storage(format!("Invalid UTF-8 in config: {}", e)))?;
                Ok(Some(config))
            },
            Ok(None) => Ok(None),
            Err(e) => Err(ModbusCollectorError::Storage(format!("Failed to get config: {}", e))),
        }
    }
    
    /// 清理过期数据
    pub async fn cleanup_expired_data(&self, retention_period: chrono::Duration) -> Result<usize> {
        let cutoff_time = Utc::now() - retention_period;
        let cutoff_timestamp = cutoff_time.timestamp_millis();
        
        let mut deleted_count = 0;
        let mut keys_to_delete = Vec::new();
        
        // 收集需要删除的键
        for item in self.data_tree.iter() {
            match item {
                Ok((key, _)) => {
                    let key_str = String::from_utf8_lossy(&key);
                    if let Some(timestamp_str) = key_str.split(':').nth(1) {
                        if let Ok(timestamp) = timestamp_str.parse::<i64>() {
                            if timestamp < cutoff_timestamp {
                                keys_to_delete.push(key.to_vec());
                            }
                        }
                    }
                },
                Err(e) => error!("Error during cleanup iteration: {}", e),
            }
        }
        
        // 删除过期数据
        for key in keys_to_delete {
            if let Err(e) = self.data_tree.remove(&key) {
                error!("Failed to delete expired data: {}", e);
            } else {
                deleted_count += 1;
            }
        }
        
        // 强制刷新到磁盘
        self.db.flush()
            .map_err(|e| ModbusCollectorError::Storage(format!("Failed to flush database: {}", e)))?;
        
        info!("Cleaned up {} expired data points", deleted_count);
        Ok(deleted_count)
    }
    
    /// 获取数据库统计信息
    pub async fn get_statistics(&self) -> Result<PersistentStorageStats> {
        let data_count = self.data_tree.len();
        let device_count = self.device_tree.len();
        let config_count = self.config_tree.len();
        
        // 获取数据库大小
        let db_size = self.estimate_db_size();
        
        Ok(PersistentStorageStats {
            data_points_count: data_count,
            devices_count: device_count,
            config_entries_count: config_count,
            db_size_mb: db_size,
        })
    }
    
    /// 估算数据库大小（MB）
    fn estimate_db_size(&self) -> f64 {
        // 这是一个简化的估算，实际可以通过文件系统获取更准确的大小
        let data_size = self.data_tree.len() * 500; // 估计每个数据点500字节
        let device_size = self.device_tree.len() * 200; // 估计每个设备状态200字节
        let config_size = self.config_tree.len() * 100; // 估计每个配置项100字节
        
        (data_size + device_size + config_size) as f64 / (1024.0 * 1024.0)
    }
    
    /// 压缩数据库
    pub async fn compact(&self) -> Result<()> {
        info!("Starting database compaction");
        
        self.db.flush()
            .map_err(|e| ModbusCollectorError::Storage(format!("Failed to flush before compaction: {}", e)))?;
        
        info!("Database compaction completed");
        Ok(())
    }
    
    /// 关闭数据库
    pub async fn close(&self) -> Result<()> {
        info!("Closing persistent storage");
        
        self.db.flush()
            .map_err(|e| ModbusCollectorError::Storage(format!("Failed to flush database: {}", e)))?;
        
        Ok(())
    }
}

/// 持久化存储统计信息
#[derive(Debug, Clone)]
pub struct PersistentStorageStats {
    pub data_points_count: usize,
    pub devices_count: usize,
    pub config_entries_count: usize,
    pub db_size_mb: f64,
}